from fastapi import FastAPI, File, UploadFile, Form

from fastapi.responses import FileResponse
import fitz
from fastapi.responses import HTMLResponse

app = FastAPI()


@app.post("/files/")
async def create_file(file: bytes = File()):
    zoom_x=10.0
    zoom_y=10.0
    rotation_angle=0
    open('data/test.pdf', 'wb').write(file)
    pdf = fitz.open("data/test.pdf")
    for pg in range(0, pdf.pageCount):
        page = pdf[pg]
        # 设置缩放和旋转系数
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)
        pm = page.getPixmap(matrix=trans, alpha=False)
        # 开始写图像
        pm.writePNG("data/"+str(pg) + ".png")
    return FileResponse('data/0.png', filename='test_0.png')

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
    zoom_x=10.0
    zoom_y=10.0
    rotation_angle=0
    open('data/test.pdf', 'wb').write(file.file.read())
    pdf = fitz.open('data/test.pdf')
    for pg in range(0, pdf.pageCount):
        page = pdf[pg]
        # 设置缩放和旋转系数
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)
        pm = page.getPixmap(matrix=trans, alpha=False)
        # 开始写图像
        pm.writePNG("data/"+str(pg) + ".png")
    return FileResponse('data/1.png', filename='test_1.png')


@app.post("/login/")
async def login(username: str = Form(), password: str = Form()):
    return {"username": username}
